<?php
/**
 * Created by PhpStorm.
 * User: Double-jin
 * Date: 2019/6/19
 * Email: 605932013@qq.com
 */

namespace App\WebSocket;

use App\Model\Token;
use App\Utility\Pool\RedisPool;

use Firebase\JWT\JWT;
use \swoole_server;
use \swoole_websocket_server;
use \swoole_http_request;
use \Exception;

/**
 * WebSocket Events
 * Class WebSocketEvents
 * @package App\WebSocket
 */
class WebSocketEvents
{


    /**
     * 打开了一个链接
     * @param swoole_websocket_server $server
     * @param swoole_http_request $request
     */
    static function onOpen(\swoole_websocket_server $server, \swoole_http_request $request)
    {

        //var_dump($request);
        //var_dump($request['cookie']['cz_access_token']);

        if ($request->cookie == null) {
            return false;
        }
        if (!array_key_exists('cz_access_token', $request->cookie)) {
            return false;
        }
        $token_str = $request->cookie['cz_access_token'];
        try {
            $deocde = JWT::decode($token_str, Token::JWTKEY, array('HS256'));
        } catch (\Exception $e) {
            return false;
        }
        //取缓存看有没对应有TOKEN
        $redis = RedisPool::defer();
        $uid = $redis->get($token_str);
        if ($uid != $deocde->uid) {
            return false;
        }

        //从缓存里取
        $redisPool = RedisPool::defer();


        $dataKline['type'] = 'k-line';
        $dataKline['val'] = $redisPool->get('cz_k_line_cache');
        $server->push($request->fd, json_encode($dataKline));


        //发5条
        $msglist = json_decode($redisPool->get('cz_finance_msg_cache'));
        foreach ($msglist as $msg) {
            $server->push($request->fd, json_encode($msg));
        }


        $dataScore = $redisPool->get('cz_score_total_cache');

        //推送
        $server->push($request->fd, $dataScore);


    }

    /**
     * 链接被关闭时
     * @param swoole_server $server
     * @param int $fd
     * @param int $reactorId
     * @throws Exception
     */
    static function onClose(\swoole_server $server, int $fd, int $reactorId)
    {

    }


}
